package com.wencai.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangpan
 * @date 2023/4/10
 */
public class IOUtils {
    public static List<String> readFromFile(String filePath) throws IOException {
        return readFromFile(filePath, "utf-8");
    }

    public static List<String> readFromFile(String filePath, String charset) throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), charset))) {
            String line;
            List<String> list = new ArrayList<>();
            while ((line = reader.readLine()) != null) {
                list.add(line);
            }
            reader.close();
            return list;
        } catch (FileNotFoundException e) {
            return new ArrayList<>();
        }
    }

    public static void writeFile(String filePath, String contnet) throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "utf-8"));
        writer.write(contnet);
        writer.close();
    }

    public static void writeFile(String filePath, String contnet, String charset) throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), charset));
        writer.write(contnet);
        writer.close();
    }


    public static List<String> readFromResource(String resource) throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(IOUtils.class.getClassLoader().getResourceAsStream(resource), "utf-8"))) {
            String line;
            List<String> list = new ArrayList<>();
            while ((line = reader.readLine()) != null) {
                list.add(line);
            }
            reader.close();
            return list;
        } catch (FileNotFoundException e) {
            return new ArrayList<>();
        }
    }
}
